package cn.jn.lhm.oss.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.jn.lhm.oss.service.OssService;
import cn.jn.lhm.oss.util.ConstantOss;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author LHM
 * @Tips 热爱每一天，奋斗每一天
 * @date 2020/5/30 - 20:18
 */
@Service
public class OssServiceImpl implements OssService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {


        //配置文件上传到阿里云的相关配置
        String endpoint = ConstantOss.ENDPOINT;
        String accessKeyId = ConstantOss.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOss.ACCESS_KEY_SECRET;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            //加上随机值，不需要对原来的文件进行覆盖
            String filename = IdUtil.simpleUUID().substring(0, 8) + file.getOriginalFilename();

            //我们希望对文件按照日期分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = datePath + "/" + filename;

            //第二个参数为：上传到OSS的文件路径
            ossClient.putObject(ConstantOss.BUCKET_NAME, filename, inputStream);
            return "https://" + ConstantOss.BUCKET_NAME + "." + endpoint + "/" + filename;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            ossClient.shutdown();
        }
    }
}
